package com.example.baselibrary.utlis

import android.graphics.Bitmap
import kotlinx.coroutines.*
import kotlinx.coroutines.launch
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.isNotEmpty


/**
 * @author 郑
 * @date 2024/6/27.
 * qq：331758871
 * phone：18979397268
 */
object SaveToFile {

    private var fileName: String? = null
    private val sdfOut: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd")
    private val sdfIn: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
    val absolutePath = ContextUtils.getContext().getExternalFilesDir(null)?.absolutePath
    //日志本地保存位置，获取日志地址
    val SAVEBASEPATH =
        absolutePath + File.separator + "KOT_ZYF_LOG" + File.separator + "KOT_ZYF_BASE" + File.separator

    fun writeLogToSDCard( type: String, context: String) {
        if (context == null) {
            return
        }
        val job = Job()
        CoroutineScope(Dispatchers.IO + job).launch {
            if (fileName == null) {
                fileName = sdfOut.format(Date(System.currentTimeMillis())) + ".txt"
            }
            val file = File(SAVEBASEPATH + fileName)
            val dateStr = sdfIn.format(Date(System.currentTimeMillis()))
            var updatedContext = "$dateStr==$type==$context"

            try {
                if (!file.exists()) {
                    file.parentFile.mkdirs()
                    file.createNewFile()
                }
                val bufferedWriter =
                    BufferedWriter(OutputStreamWriter(FileOutputStream(file, true)))
                bufferedWriter.write(updatedContext)
                bufferedWriter.newLine()
                bufferedWriter.flush()
                bufferedWriter.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        job.cancel()
    }

    fun writeIpToSDCard(saveName: String, message: String) {
        val job = Job()
        CoroutineScope(Dispatchers.IO + job).launch {
            val file = File(saveName + "IpConfig.txt")
            try {
                if (!file.exists()) {
                    file.parentFile.mkdirs()
                    file.createNewFile()
                }
                val bufferedWriter =
                    BufferedWriter(OutputStreamWriter(FileOutputStream(file, true)))
                bufferedWriter.write(message)
                bufferedWriter.newLine()
                bufferedWriter.flush()
                bufferedWriter.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        job.cancel()
    }

    // 指纹图片存放路径
    var sdCardDir = SAVEBASEPATH
    val file = File(
        sdCardDir,
        "Screen" + TimeHelpUtils.getLocationTimeNew(TimeHelpUtils.FORMAT_TIME_CN) + ".jpg"
    )

    /**
     * 保存指纹图片
     *
     * @param bitmap
     */
    fun saveBitmap(bitmap: Bitmap) {
        if (bitmap == null || bitmap.isRecycled || bitmap.byteCount <= 0) {
            LogUtils.logEvent("保存图片失败，图片为空")
            return
        }
        val job = CoroutineScope(Dispatchers.IO).launch {
            try {
                val launch = CoroutineScope(Dispatchers.IO).launch {
                    val dirFile = File(sdCardDir)
                    if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                        dirFile.mkdirs()
                    }
                    //判断文件夹下是否有文件，有就删除
                    val files = dirFile.listFiles()
                    if (files != null && files.isNotEmpty()) {
                        for (file in files) {
                            file.delete()
                        }
                    }
                }
                launch.join()
                val fos = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
                fos.close()
                launch.cancel()
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
                LogUtils.logEvent("保存图片失败，找不到文件" + e.message)
            } catch (e: IOException) {
                e.printStackTrace()
                LogUtils.logEvent("保存图片失败，IO异常" + e.message)
            }
        }
        job.cancel()
    }
}

